package com.gcxy.springmybatisplustest.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gcxy.springmybatisplustest.converter.StringToOrderConverter;
import com.gcxy.springmybatisplustest.domain.entity.Orders;
import com.gcxy.springmybatisplustest.domain.result.ApiResponse;
import com.gcxy.springmybatisplustest.domain.vo.OrderVO;
import com.gcxy.springmybatisplustest.exception.BusinessException;
import com.gcxy.springmybatisplustest.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private IOrderService orderService;

    @GetMapping("/list")
    public ApiResponse<List<OrderVO>> list(){
        if (true){
            throw new BusinessException("这是BusinessException异常");
        }
        StringToOrderConverter stringToOrderConverter = new StringToOrderConverter();
        List<OrderVO> voList = new ArrayList<>();
        for (Orders order: orderService.list()){
            String convert = stringToOrderConverter.convert(order.getStatus());
            OrderVO orderVO = BeanUtil.copyProperties(order, OrderVO.class);
            orderVO.setStatus(convert);
            voList.add(orderVO);
        }
        return ApiResponse.success(voList);
    }

    @PostMapping("/addOrder")
    public ApiResponse addOrder(@RequestBody @Validated Orders order){
        orderService.save(order);
        return ApiResponse.success("添加成功");
    }

    @PutMapping("/update")
    public ApiResponse update(@RequestParam Integer orderId,@RequestParam Integer status){

        LambdaUpdateWrapper<Orders> wrapper = new LambdaUpdateWrapper<Orders>()
                .eq(Orders::getId,orderId)
                .eq(Orders::getStatus,status);

        orderService.update(wrapper);
        return ApiResponse.success("更新成功");
    }

    @DeleteMapping("/delete")
    public ApiResponse delete(@RequestParam Integer orderId){
        orderService.removeById(orderId);
        return ApiResponse.success("删除成功");
    }
}
